package com.hwpt.hwaccount.feature.splash;

import com.hwpt.hwaccount.core.data.local.entity.UserEntity;
import com.hwpt.hwaccount.core.utils.JwtUtils;

import java.util.List;

/**
 * 引导页Presenter层实现，负责业务逻辑处理
 */
public class SplashPresenter implements SplashContract.Presenter {

    private final SplashContract.View view;
    private final SplashContract.Model model;

    public SplashPresenter(SplashContract.View view, SplashContract.Model model) {
        this.view = view;
        this.model = model;
    }

    @Override
    public void start() {
        checkUserStatus();
    }

    @Override
    public void checkUserStatus() {
        model.getAllUsers(new SplashContract.Model.OnUserInfoCallback() {
            @Override
            public void onSuccess(List<UserEntity> userEntities) {

                if (userEntities != null && !userEntities.isEmpty()) {
                    UserEntity currentUser = userEntities.get(0);
                    String accountId = currentUser.getHanWangId();
                    String token = currentUser.getToken();
                    boolean isTokenValid = JwtUtils.validateToken(token);

                    if (accountId != null||isTokenValid) {
                        view.navigateToHome();
                    } else {
                        view.navigateToLogin();
                    }
                } else {
                    view.navigateToLogin();
                }
            }

            @Override
            public void onError(Throwable e) {
                view.showError("用户状态校验失败: " + e.getMessage());
                view.navigateToLogin();
            }
        });
    }

    @Override
    public void destroy() {
        if (model instanceof SplashModel) {
            ((SplashModel) model).dispose();
        }
    }
}
